namespace Pay.Core {
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Web;

    public class StringHelper {
        public static int GetStringLength(string s) {
            if (!string.IsNullOrEmpty(s)) {
                return Encoding.Default.GetBytes(s).Length;
            }
            return 0;
        }

        public static int IndexOf(string s, int order) {
            return IndexOf(s, '-', order);
        }

        public static int IndexOf(string s, char c, int order) {
            int length = s.Length;
            for (int i = 0; i < length; i++) {
                if (c == s[i]) {
                    if (order == 1) {
                        return i;
                    }
                    order--;
                }
            }
            return -1;
        }

        public static string[] SplitString(string sourceStr) {
            return SplitString(sourceStr, ",");
        }

        public static string[] SplitString(string sourceStr, string splitStr) {
            if (string.IsNullOrEmpty(sourceStr) || string.IsNullOrEmpty(splitStr)) {
                return new string[0];
            }
            if (sourceStr.IndexOf(splitStr) == -1) {
                return new string[] { sourceStr };
            }
            if (splitStr.Length == 1) {
                return sourceStr.Split(new char[] { splitStr[0] });
            }
            return Regex.Split(sourceStr, Regex.Escape(splitStr), RegexOptions.IgnoreCase);
        }

        public static string SubString(string sourceStr, int length) {
            return SubString(sourceStr, 0, length);
        }

        public static string SubString(string sourceStr, int startIndex, int length) {
            if (!string.IsNullOrEmpty(sourceStr)) {
                if (sourceStr.Length >= (startIndex + length)) {
                    return sourceStr.Substring(startIndex, length);
                }
                return sourceStr.Substring(startIndex);
            }
            return "";
        }

        public static string Trim(string sourceStr, string trimStr) {
            return Trim(sourceStr, trimStr, true);
        }

        public static string Trim(string sourceStr, string trimStr, bool ignoreCase) {
            if (string.IsNullOrEmpty(sourceStr)) {
                return string.Empty;
            }
            if (!string.IsNullOrEmpty(trimStr)) {
                if (sourceStr.StartsWith(trimStr, ignoreCase, CultureInfo.CurrentCulture)) {
                    sourceStr = sourceStr.Remove(0, trimStr.Length);
                }
                if (sourceStr.EndsWith(trimStr, ignoreCase, CultureInfo.CurrentCulture)) {
                    sourceStr = sourceStr.Substring(0, sourceStr.Length - trimStr.Length);
                }
            }
            return sourceStr;
        }

        public static string TrimEnd(string sourceStr, string trimStr) {
            return TrimEnd(sourceStr, trimStr, true);
        }

        public static string TrimEnd(string sourceStr, string trimStr, bool ignoreCase) {
            if (string.IsNullOrEmpty(sourceStr)) {
                return string.Empty;
            }
            if (!(!string.IsNullOrEmpty(trimStr) && sourceStr.EndsWith(trimStr, ignoreCase, CultureInfo.CurrentCulture))) {
                return sourceStr;
            }
            return sourceStr.Substring(0, sourceStr.Length - trimStr.Length);
        }

        public static string TrimStart(string sourceStr, string trimStr) {
            return TrimStart(sourceStr, trimStr, true);
        }

        public static string TrimStart(string sourceStr, string trimStr, bool ignoreCase) {
            if (string.IsNullOrEmpty(sourceStr)) {
                return string.Empty;
            }
            if (!(!string.IsNullOrEmpty(trimStr) && sourceStr.StartsWith(trimStr, ignoreCase, CultureInfo.CurrentCulture))) {
                return sourceStr;
            }
            return sourceStr.Remove(0, trimStr.Length);
        }
        public static string ReplaceHtmlTag(string html, int length = 0) {
            string strText = Regex.Replace(html, "<[^>]+>", "");
            strText = Regex.Replace(strText, "&[^;]+;", "");

            if (length > 0 && strText.Length > length)
                return strText.Substring(0, length);

            return strText;
        }

        /// <summary>
        /// 生成随机字母字符串(数字字母混和)
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        public static string RandomString(int count) {
            int number;
            string checkCode = String.Empty;     //存放随机码的字符串   

            Random random = new Random();

            for (int i = 0; i < count; i++) //产生4位校验码   
            {
                number = random.Next();
                number = number % 36;
                if (number < 10) {
                    number += 48;    //数字0-9编码在48-57   
                } else {
                    number += 55;    //字母A-Z编码在65-90   
                }

                checkCode += ((char)number).ToString();
            }
            return checkCode;
        }
        /// <summary>
        /// 获取客户端IP地址（无视代理）
        /// </summary>
        /// <returns>若失败则返回回送地址</returns>
        public static string GetHostAddress() {
            string userHostAddress = HttpContext.Current.Request.UserHostAddress;

            if (string.IsNullOrEmpty(userHostAddress)) {
                userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            //最后判断获取是否成功，并检查IP地址的格式（检查其格式非常重要）
            if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress)) {
                return userHostAddress;
            }
            return "127.0.0.1";
        }

        /// <summary>
        /// 检查IP地址格式
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(string ip) {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        public static string StringToImgUrl(string content, string domain) {
            string pattern = @"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>";
            content = Regex.Replace(content, pattern, (c => {
                string newValue = string.Empty;
                string oldImgUrl = c.Groups["imgUrl"].Value;
                if (!String.IsNullOrEmpty(oldImgUrl)) {
                    string imgUrl = domain + oldImgUrl;//需要替换的图片地址
                    newValue = c.Value.Replace(oldImgUrl, imgUrl);
                }
                return newValue;
            }));
            return content;
        }

        /// <summary>
        /// 物流公司编码转换
        /// </summary>
        /// <param name="express_code"></param>
        /// <returns></returns>
        public static string ReplaceExpressCode(string express_code) {
            #region 候鸟物流公司编码
            /*
             [
        {
            "name":"安能小包",
            "code":"annengwuliu"
        },
        {
            "name":"全峰快递",
            "code":"quanfengkuaidi"
        },
        {
            "name":"国际物流",
            "code":"guoji"
        },
        {
            "name":"快捷速递",
            "code":"kuaijiesudi"
        },
        {
            "name":"八达通快递",
            "code":"badatong"
        },
        {
            "name":"Track Parcel",
            "code":"trackparcel"
        },
        {
            "name":"品骏快递",
            "code":"pjbest"
        },
        {
            "name":"中国邮政",
            "code":"youzhengguonei"
        },
        {
            "name":"ewe全球快递",
            "code":"ewe"
        },
        {
            "name":"中联速递",
            "code":"auvanda"
        },
        {
            "name":"西翼物流",
            "code":"westwing"
        },
        {
            "name":"货运皇物流",
            "code":"kingfreight"
        },
        {
            "name":"洋包裹",
            "code":"yangbaoguo"
        },
        {
            "name":"全一快递",
            "code":"quanyikuaidi"
        },
        {
            "name":"方舟国际速递",
            "code":"arkexpress"
        },
        {
            "name":"澳世速递",
            "code":"ausexpress"
        },
        {
            "name":"转运四方",
            "code":"zhuanyunsifang"
        },
        {
            "name":"澳德快递",
            "code":"auodexpress"
        },
        {
            "name":"蓝天速递",
            "code":"blueskyexpress"
        },
        {
            "name":"AOL澳通快递",
            "code":"aolau"
        },
        {
            "name":"EASY国际速递",
            "code":"easyexpress"
        },
        {
            "name":"PCA国际速递",
            "code":"pcaexpress"
        },
        {
            "name":"易境达国际物流",
            "code":"uscbexpress"
        },
        {
            "name":"递四方",
            "code":"disifang"
        },
        {
            "name":"三象速递",
            "code":"sxexpress"
        },
        {
            "name":"澳邦国际物流",
            "code":"ausbondexpress"
        },
        {
            "name":"急递速递",
            "code":"jdexpress"
        },
        {
            "name":"UEQ快递",
            "code":"ueq"
        },
        {
            "name":"美西快递",
            "code":"mx"
        },
        {
            "name":"安达速递",
            "code":"adapost"
        },
        {
            "name":"斑马物流",
            "code":"banma"
        },
        {
            "name":"优邦速运",
            "code":"ubonex"
        },
        {
            "name":"中环快递",
            "code":"zhonghuan"
        },
        {
            "name":"澳邮中国快运",
            "code":"auexpress"
        },
        {
            "name":"驿扬国际速运",
            "code":"iyoungspeed"
        },
        {
            "name":"泰兴国际物流",
            "code":"taixing"
        },
        {
            "name":"TST速运通",
            "code":"tstexp"
        },
        {
            "name":"豪杰快递",
            "code":"hjusaexpress"
        },
        {
            "name":"极地快递",
            "code":"polarexpress"
        },
        {
            "name":"增速海淘",
            "code":"zyzoom"
        },
        {
            "name":"程光快递",
            "code":"flyway"
        },
        {
            "name":"易达通快递",
            "code":"qexpress"
        },
        {
            "name":"长江国际速递",
            "code":"changjiang"
        },
        {
            "name":"新元快递",
            "code":"xingyuan"
        },
        {
            "name":"跨境直邮通",
            "code":"kjde"
        },
        {
            "name":"淘布斯国际物流",
            "code":"taoplus"
        },
        {
            "name":"捷安达国际速递",
            "code":"jieanda"
        }
    ]
             */
            #endregion
            var expresses = new Dictionary<string, string>();
            expresses.Add("eems", "EMS");
            expresses.Add("ems", "EMS");
            expresses.Add("guotongkuaidi", "GTO");//国通快递
            expresses.Add("yuantong", "YTO");//圆通速递
            expresses.Add("zhongtong", "ZTO");//中通速递
            expresses.Add("yunda", "YD");//韵达快递
            expresses.Add("shunfeng", "SF");//顺丰快递
            expresses.Add("shentong", "STO");//申通快递
            expresses.Add("youzhengguonei", "YZPY");//邮政平邮/小包
            expresses.Add("tiantian", "HHTT");//天天快递
            expresses.Add("youshuwuliu", "UC");//优速快递
            expresses.Add("baishiwuliu", "HTKY");//百世快运
            expresses.Add("debangwuliu", "DBL");//德邦
            expresses.Add("huitongkuaidi", "HTKY");//百世汇通
            expresses.Add("jd", "JD");//京东
            expresses.Add("sewl", "SURE");//速尔快递
            bool has_express = expresses.ContainsKey(express_code);
            return (has_express ? expresses[express_code] : express_code);
        }

        /// <summary>
        /// 字符串脱敏
        /// </summary>
        /// <param name="rawContent"></param>
        /// <returns></returns>
        public static string StringDesensitization(string rawContent) {
            var result = rawContent;
            if (!string.IsNullOrEmpty(result)) {
                if (result.Length > 3) {
                    int beginPos = (int)(result.Length * 0.3);
                    int endPos = (int)(result.Length * 0.7);
                    int tempLength = endPos - beginPos;
                    string tempStr = string.Empty;
                    for (int i = 0; i < tempLength; i++) {
                        tempStr += "*";
                    }

                    result = result.Substring(beginPos, tempLength);
                    result = result.Insert(beginPos, tempStr);
                } else {
                    result = result.Substring(0, 1);
                    result = result.Insert(1, "*");
                }
            }
            return result;
        }
    }
}